﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class user_ViewCart : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            LoadCart();
        }

    }
    public void LoadCart()
    {
        grvCart.DataSource = ShoppingCart.Instance.Items;
        grvCart.DataBind();
    }

    protected void grvCart_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "remove")
        {
            int idProduct = Convert.ToInt32(e.CommandArgument);
            ShoppingCart.Instance.RemoveItem(idProduct);
        }
        LoadCart();
    }
    protected void btnUpdateCart_Click(object sender, EventArgs e)
    {
        
        foreach (GridViewRow row in grvCart.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                try
                {
                    //lay id
                    int idProduct = Convert.ToInt32(grvCart.DataKeys[row.RowIndex].Value);
                    //tim textbox quantity va set gia tri
                    int quantity = int.Parse(((TextBox)row.Cells[2].FindControl("txtQuantity")).Text);
                    ShoppingCart.Instance.SetItemQuantity(idProduct, quantity);
                }
                catch (Exception)
                {

                }
            }
        }

        LoadCart();
    }
    protected void grvCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[4].Text = "Total: " + String.Format("{0:0.0.0} $", ShoppingCart.Instance.GetSubTotal());
        }
    }

    protected void btnCheckout_Click(object sender, EventArgs e)
    {
        if (ShoppingCart.Instance.Items.Count>0)
        {
          
            Response.Redirect("checkout.aspx");
            
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, typeof(Page), "Messages", "<script>alert('Shopping cart empty!')</script>", false);
        }
    }

}